package com.culture.bootdemo.controller.queue;

import lombok.Data;

import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * @author: wen
 * @date: 2023/6/27 10:50
 * DelayQueue 延迟队列：只能添加(offer/put/add)实现了Delayed接口的对象
 */
@Data
public class DelayQueueDemo2 implements Delayed {

    private String name;
    private long time;


    public DelayQueueDemo2(String name, long time) {
        this.name = name;
        //time =当前时间+ delayTime
        this.time = System.currentTimeMillis() + time;
    }


    /**
     * 需要实现的接口，获得延迟时间   用过期时间-当前时间
     *
     * @param unit
     * @return
     */
    @Override
    public long getDelay(TimeUnit unit) {
        //判断time是否大于当前系统时间，并将结果转换成MILLISECONDS
        return unit.convert(time - System.currentTimeMillis(), TimeUnit.MILLISECONDS);
    }

    /**
     * 用于延迟队列内部比较排序   当前时间的延迟时间 - 比较对象的延迟时间
     * 获取剩余时间
     *
     * @param o
     * @return
     */
    @Override
    public int compareTo(Delayed o) {
        //以下两种方式都可以
//        return (int) (this.getDelay(TimeUnit.MILLISECONDS) - o.getDelay(TimeUnit.MILLISECONDS));
        return (int) (this.time - ((DelayQueueDemo2) o).getTime());
    }


    private static DelayQueue delayQueue = new DelayQueue();

    public static void main(String[] args) throws InterruptedException {

        delayQueue.offer(new DelayQueueDemo2("task1", 10000L));
        delayQueue.offer(new DelayQueueDemo2("task2", 3000L));
        delayQueue.offer(new DelayQueueDemo2("task3", 1000L));
        delayQueue.offer(new DelayQueueDemo2("task4", 5000L));
        delayQueue.offer(new DelayQueueDemo2("task5", 6000L));
        delayQueue.offer(new DelayQueueDemo2("task6", 7000L));
        delayQueue.offer(new DelayQueueDemo2("task7", 4000L));

        while (!delayQueue.isEmpty()) {
            Delayed take = delayQueue.take();
            System.out.println(take);
        }
    }
}
